<?php
/**
 * Created by PhpStorm.
 * User: 张辉
 * Date: 2018/7/13
 * Time: 13:50
 */

/**
 * Class TokenDataCountService   币种数据统计
 */
namespace app\common\service;

class TokenDataCountService
{
    /**
     * 用户持仓总量统计
     * @param int $top 统计前多少位
     * @return array
     */
    public function userCoinCountTop( $top = 100 )
    {
        $userCoinModel = UserCoinModel::getInstance();

        // @todo 暂时先这样统计排行  后期再优化
        $list = $userCoinModel
//            ->field("sum(user_coin.amount) as amount,coin_token.symbol")
            ->join("left join coin_token on user_coin.coin_id=coin_token.id")
            ->group("user_coin.coin_id")
            ->order("amount desc")
            ->limit( $top )->getField("coin_token.id,coin_token.symbol,coin_token.cht_name,coin_token.en_name,sum(user_coin.amount) as amount,count(*) as count");

        // 获取获取已发布文章列表
        $publishArticleModel = PublishArticleModel::getInstance();
        $map = [
        		'deleted' => - 1,
        		'status' => 1,
        		'is_published' => 1,
        		'is_tmp' => -1,
        		"article_type" => array( 'neq', PublishArticleModel::CMS_TYPE_DATADAILY ),
        ];

        $article_list = $publishArticleModel->muti_get_data_by_where( $map, true, true, false );
        $article_count_list = [];
        $time = strtotime( date('Y-m-d') );

        // token下文章统计
        foreach ( $article_list as $value ){
            if ( !$value['coin_list'] ){
                continue;
            }

            foreach ( $value['coin_list'] as $v ){
                if ( !isset( $article_count_list[$v] ) ){
                    $article_count_list[$v] = [
                        'article_count' => 0,
                        'today_article_count'  => 0,
                    ];
                }

                $article_count_list[$v]['article_count'] ++;
                if ( strtotime( $value['create_time'] ) > $time){
                    $article_count_list[$v]['today_article_count'] ++;
                }
            }
        }


        foreach ( $list as $key => &$value){
            $value['article_count'] = isset( $article_count_list[$key] ) ? $article_count_list[$key]['article_count'] : 0;
            $value['today_article_count'] = isset( $article_count_list[$key] ) ? $article_count_list[$key]['today_article_count'] : 0;
            $value['amount'] = number_format( $value['amount'], 4, '.', '');
        }

        return $list?: [];
    }

    /**
     * 用户持仓token类型数统计
     * @return array
     */
    public function userCoinTypeCount()
    {
        $userCoinModel = UserCoinModel::getInstance();
        $list = $userCoinModel
            ->field("count(*) as count,user_id")
            ->group( "user_id" )
            ->order( "count desc" )
            ->select();
        return $list ?: [];
    }

    /**
     * 用户交易对统计
     * @return array
     */
    public function userPairCount()
    {
        $userPairModel = UserPairModel::getInstance();
        $list = $userPairModel
            ->field("count(*) as count,pair_runtime.symbol,pair_runtime.pair_name")
            ->join("left join pair_runtime on user_pair.pair_id=pair_runtime.id")
            ->group("pair_id")
            ->order("count desc")
            ->select();
        return $list ?: [];
    }



    /**
     * 交易所对应交易对数据统计
     */
    public function exchangeCount()
    {
        $coinRuntimeModel = CoinRuntimeModel::getInstance();
        $list = $coinRuntimeModel->get_zb_exchange_pair_list_all();
        // 处理交易对数据

        // 获取所有token列表
        $tokenModel = CoinRuntimeModel::getInstance();
        $token_list = $tokenModel->get_key_value("id", "symbol" );
        $token_count = count( $token_list );
        $list_format = [];

        foreach ( $list as $exchange_name => $exchange ){
            $exchange_count = [
                // 交易所交易对个数
                "pair_count"  => count( $exchange ),
                // 交易所名称
                "title"       => $exchange_name,
                // 交易所token覆盖数
                "exchange_token_count"  => 0,

                // 平台Token总数
                "token_count"  => $token_count,

                // 交易所token列表
                "exchange_token_list"  => [],

                // 覆盖度
                "coverage"    => "0%",
            ];

            // 统计交易token
            foreach ( $exchange as $pair ){
                $token = explode( "-", $pair[1] );
                foreach ( $token as $token_id ){
                    $token_symbol = $token_list[$token_id];
                    $exchange_count["exchange_token_list"][$token_symbol] = $token_symbol;
                }
            }

            $exchange_count['exchange_token_count'] = count( $exchange_count['exchange_token_list'] );
            $exchange_count['coverage'] = bcmul( bcdiv( $exchange_count['exchange_token_count'], $token_count,4 ), 100, 2)."%";
            $list_format[ $exchange_name ] = $exchange_count;
        }

        return CommonFun::sortArr( $list_format,"pair_count", SORT_DESC );
    }

    /**
     * 新增持仓币种统计
     */
    public function userNewCoinCount( $start_time = '', $end_time = '' )
    {
        $userCoinModel = UserCoinModel::getInstance();

        $where = array(
            "user_coin.create_time" =>array("between", array( $start_time, $end_time ) ),
        );

        $list = $userCoinModel
            ->where( $where )
            ->join("left join coin_token on user_coin.coin_id=coin_token.id")
            ->group("user_coin.coin_id")
            ->order("amount desc")
            ->getField("coin_token.id,coin_token.symbol,sum(user_coin.amount) as amount,count(*) as count");

        $list = $list ?: [];
        $list_format = [];

        $where =  array(
            "create_time" =>array("not between", array( $start_time, $end_time ) ),
        );

        // 获取获取已发布文章列表
        $publishArticleModel = PublishArticleModel::getInstance();

        foreach ( $list as $key => $value ){
            $where['coin_id'] = $key;
            $info =  $userCoinModel
                ->where( $where )
                ->count();
            if ( $info ){
                continue;
            }

            $map = [
                'deleted' => -1,
                '_string' => CommonModel::search_json_array( $key, 'coin_list' ),
            ];

            $article_count = $publishArticleModel->where( $map )->count();
            $value['article_count'] = $article_count;

            $list_format[$key] = $value;
        }

        return CommonFun::sortArr( $list_format,"amount", SORT_DESC );

    }

    /**
     * DAU数据统计
     */
    public function DAUDataCount( $start_time, $end_time )
    {
        // 统计数组
        $data_list = array();

        // 获取间隔时间
        $date_list = CommonFun::getTimeStampIntervalDate( strtotime( $start_time ), strtotime($end_time) );

        $mtaAndroidApiService = new MtaApiService();
        $android_mta_list = $mtaAndroidApiService->getAppBasicsInfo( $start_time, $end_time );

        $mtaApiService = new MtaApiService( "ios" );
        $ios_mta_list = $mtaApiService->getAppBasicsInfo( $start_time, $end_time );


        // 获取注册用户数据
        $modelUserBase = UserBaseModel::getInstance();

        $where = array(
            "create_time" =>array("between", array( $start_time, $end_time.' 23:59:59')),
        );

        // 获取用户注册数据
        $userCountList = $modelUserBase->where($where)->field("count(*) as count,FROM_UNIXTIME(unix_timestamp(create_time),'%Y-%m-%d') as date,register_type")->group('date,register_type')->select();
        $userCountListFormat = [];

        // 组合用户注册数据
        foreach ( $userCountList as $value ){
            if( !isset($userCountListFormat[$value['date']]) ){
                $userCountListFormat[$value['date']] = [
                    'h5'       =>  0,
                    'android'  =>  0,
                    'ios'      =>  0,
                ];
            }

            $userCountListFormat[$value['date']][$value['register_type']] = $value['count'];
        }

        // 获取活跃用户数据
        $apiLogModel = new ApiLogMongo();

        // 设置搜索条件
        $apiLogModel->where_between("request_time", strtotime( $start_time ), strtotime( $end_time ) + 86399 );
        $apiLogModel->where_gt("user_id",'0');
        $apiLogModel->where_in("group", array("Article","Coin","Jsapi"));
        $apiLogModel->where_in("module", array("Article","Info"));
        $apiLogModel->where_in("method", array("get","POST"));
        $apiLogModel->field( array( 'request_time','headers','Clienttype','user_id' ) );
        // 获取数据
        $api_data_list = $apiLogModel->get();

        $api_data_list_format = array();

        if ( $api_data_list ) {
            $req_list = array();
            foreach ( $api_data_list as $v ) {
                if ( !isset($v['request_time']) || !$v['request_time'] ) {
                    continue;
                }
                $date = date("Y-m-d", $v['request_time']);
                $headers_arr = json_decode($v['headers'], true);
                $client_type = isset($headers_arr['Clienttype']) ? $headers_arr['Clienttype'] : 'h5' ;
                // 排除app打开的文章
                if ( $client_type=="h5" && isset($headers_arr['X-Requested-With']) && $headers_arr['X-Requested-With']=="com.ihold.hold" ) {
                	continue;
                }
                $user_id = $v['user_id'];
                $req_list[$date][$client_type][] = $user_id;
            }
            foreach ( $req_list as $_date=>$_rv ) {
                if ( !isset($api_data_list_format[$_date]) ) {
                    $api_data_list_format[$_date] = array(
                        "date" => $_date,
                        "android" => 0,
                        "ios" => 0,
                        "h5" => 0,
                        "total" => 0,
                    );
                }
                foreach ( $_rv as $_ctype=>$_cliUser ) {
                    $count = count(array_unique($_cliUser));
                    $api_data_list_format[$_date][$_ctype] += $count;
                    $api_data_list_format[$_date]["total"] += $count;
                }
            }
        }



        // 组合显示数据
        foreach ( $date_list as $value ){

            $android = [
                'date' =>         $value,
                'client_type'     => 'android',
                'noRepeatUser'    =>  isset( $android_mta_list[$value] ) ? $android_mta_list[$value]['NoRepeatUser'] : 0, // 无重复安装新用户
                'activeUser'      =>  isset( $android_mta_list[$value] ) ? $android_mta_list[$value]['ActiveUser'] : 0, // 活跃用户
                'serviceRegisterUser'    =>  isset( $userCountListFormat[$value] ) ? $userCountListFormat[$value]['android'] : 0, // 服务端注册用户
                'serviceActiveUser'      =>  isset( $api_data_list_format[$value] ) ? $api_data_list_format[$value]['android'] : 0, // 服务端活跃用户
            ];

            $ios = [
                'date' =>         $value,
                'client_type'     => 'ios',
                'noRepeatUser'    =>  isset( $ios_mta_list[$value] ) ? $ios_mta_list[$value]['NoRepeatUser'] : 0, // 无重复安装新用户
                'activeUser'      =>  isset( $ios_mta_list[$value] ) ? $ios_mta_list[$value]['ActiveUser'] : 0, // 活跃用户
                'serviceRegisterUser'    =>  isset( $userCountListFormat[$value] ) ? $userCountListFormat[$value]['ios'] : 0, // 服务端注册用户
                'serviceActiveUser'      =>  isset( $api_data_list_format[$value] ) ? $api_data_list_format[$value]['ios'] : 0, // 服务端活跃用户
            ];

            $h5 = [
                'date' =>         $value,
                'client_type'     => 'h5',
                'noRepeatUser'    =>  0,
                'activeUser'      =>  0,
                'serviceRegisterUser'    =>  isset( $userCountListFormat[$value] ) ? $userCountListFormat[$value]['h5'] : 0, // 服务端注册用户
                'serviceActiveUser'      =>  isset( $api_data_list_format[$value] ) ? $api_data_list_format[$value]['h5'] : 0, // 服务端活跃用户
            ];

            // 安卓 + ios
            $android_ios = [
                'date' =>         $value,
                'client_type'     => 'android + ios',
                'noRepeatUser'    =>  $android['noRepeatUser'] + $ios['noRepeatUser'],
                'activeUser'      =>  $android['activeUser'] + $ios['activeUser'],
                'serviceRegisterUser'    =>  $android['serviceRegisterUser'] + $ios['serviceRegisterUser'],
                'serviceActiveUser'      =>  $android['serviceActiveUser'] + $ios['serviceActiveUser'],
            ];


            $android_ios['registerUserProportion'] = floatval( bcmul(bcdiv( $android_ios['serviceRegisterUser'] ?: 1, $android_ios['noRepeatUser'],4),100) ).'%';
            $android_ios['activeUserProportion'] = floatval( bcmul(bcdiv( $android_ios['serviceActiveUser'] ?: 1, $android_ios['activeUser'], 4),100) ).'%';

            $android['registerUserProportion'] = floatval( bcmul(bcdiv( $android['serviceRegisterUser'] ?: 1, $android['noRepeatUser'],4),100) ).'%';
            $android['activeUserProportion'] = floatval( bcmul(bcdiv( $android['serviceActiveUser'] ?: 1, $android['activeUser'],4),100) ).'%';

            $ios['registerUserProportion'] = floatval( bcmul(bcdiv( $ios['serviceRegisterUser'] ?: 1, $ios['noRepeatUser'],4),100) ).'%';
            $ios['activeUserProportion'] = floatval( bcmul(bcdiv( $ios['serviceActiveUser'] ?: 1, $ios['activeUser'],4),100) ).'%';

            $h5['registerUserProportion'] = 0;
            $h5['activeUserProportion'] = 0;

            $data_list[] = $android_ios;
            $data_list[] = $android;
            $data_list[] = $ios;
            $data_list[] = $h5;
        }

        return $data_list;

    }

    /**
     * 获取用户持仓统计
     */
    public static function get_user_coin_count()
    {
        $userCoinModel = UserCoinModel::getInstance();
        $userPairModel = UserPairModel::getInstance();
        $pairRuntimeModel = PairRuntimeModel::getInstance();
        $userBaseModel = UserBaseModel::getInstance();
        $pair_list = $pairRuntimeModel->get_key_value( 'id', 'base');

        $where = array(
            'last_time' => array( 'GT' , date('Y-m-d H:i:s', time() - 86400 * 15 ))
        );

        // 获取活跃用户id列表
        $user_id_list = $userBaseModel->search_id_list_no_page( $where );
        $where = $user_id_list ? array('user_id' => array( 'in', $user_id_list ) ) : array();

        // @todo 暂时先这样统计排行  后期再优化
        $list = $userCoinModel
//            ->field("sum(user_coin.amount) as amount,coin_token.symbol")
                ->where( $where )
            ->group("coin_id")
            ->getField("coin_id,count(*) as count");

        $wxCoinModel = WeChatUserCoinModel::getInstance();

        $listPair = $userPairModel
//            ->field("sum(user_coin.amount) as amount,coin_token.symbol")
            ->where( $where )
            ->group("pair_id")
            ->getField("pair_id,count(*) as count");


        $list2 = $wxCoinModel
//            ->field("sum(user_coin.amount) as amount,coin_token.symbol")
            ->group("coin_id")
            ->getField("coin_id,count(*) as count");
        
            $list2 = $list2?:[];
        foreach ( $list2 as $key => $value ){
            if( isset( $list[$key] ) ){
                $list[$key] += $value;
            } else {
                $list[$key] = $value;
            }
        }

        $listPair = $listPair?:[];
        foreach ( $listPair as $key => $value ){
        	if ( isset($pair_list[$key]) ) {
        		$coin_id = $pair_list[$key];
        	}else {
        		continue;
        	}
            
            if( isset( $list[$coin_id] ) ){
                $list[$coin_id] += $value;
            } else {
                $list[$coin_id] = $value;
            }
        }

        $id_list = array_keys($list);
        $coin_model = CoinRuntimeModel::getInstance();
        $coin_symbol_list = $coin_model->get_key_value( 'id','symbol',array('id'=>array('in',$id_list)));

        arsort($list);
        $list_format = array();
        foreach ( $list as $key => $value ){
            if ( !isset($coin_symbol_list[$key]) ){
                continue;
            }

            $list_format[$key] =  array(
                'id' => $key,
                'symbol' => $coin_symbol_list[$key],
                'count'  => $value,
                'content_count' => 0
            );
        }

        return $list_format;
    }

    /**
     * 获取近两天用户持仓统计
     */
    public static function get_user_coin_num($coin_list)
    {
        if (!$coin_list) {
            return false;
        }
        $userPairModel    = UserPairModel::getInstance();
        $pairRuntimeModel = PairRuntimeModel::getInstance();
        $wxCoinModel      = WeChatUserCoinModel::getInstance();
        $weChatUserModel  = WeChatUserModel::getInstance();
        $modelUserBase    = UserBaseModel::getInstance();
        //两天注册的app用户和微信用户
        $user_map['create_time'] = ['gt', date('Y-m-d H:i:s', time() - 86400 * 2 )];
        $auids  = $modelUserBase->search_id_list_no_page($user_map);
        $wuids  = $weChatUserModel->search_id_list_no_page($user_map);

        //交易对关注的用户
        $user_map['deleted']   = -1;
        if ( $auids ) {
        	$user_map['user_id']   = ['in', $auids];
        }
        $pair_ids =  $userPairModel->where($user_map)->group('pair_id')->getField("pair_id,count(*) as count");
        $pair_coinids = [];
        if ($pair_ids) {
            foreach ($pair_ids as $k => $v) {
                $res = $pairRuntimeModel->get_data_by_id($k);
                $pair_coinids[$res['base']] =  $v; 
            }
        }
        //微信关注的
        $wechat_map['coin_id']     = ['gt', 0];
        if ( $wuids ) {
        	$wechat_map['wechat_user_id'] = ['in', $wuids];
        }
        $wechat_map['create_time'] = ['gt', date('Y-m-d H:i:s', time() - 86400 * 2 )];
        $wechat_uids =  $wxCoinModel->where( $wechat_map )->group("coin_id")->getField("coin_id,count(*) as count");

        if ($coin_list) {
            foreach ($coin_list as $coin_id=>$coin) {
                if (array_key_exists($coin_id,  $pair_coinids)) {
                    $coin_list[$coin_id]['follow_users']  = $pair_coinids[$coin_id];
                    if (array_key_exists($coin_id,  (array)$wechat_uids)) {
                        $coin_list[$coin_id]['follow_users'] = $pair_coinids[$coin_id] +  $wechat_uids[$coin_id];
                    }
                } else {
                     $coin_list[$coin_id]['follow_users'] = 0;
                }
            }
        };
        return $coin_list;

    }
















}